<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :search.sync="search"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot-scope="" slot="partNoSearch">
        <el-input placeholder="请选择 料号" readonly="true" v-model="search.partNo">
          <el-button slot="append" icon="el-icon-search" @click="openPartCommonModal"></el-button>
        </el-input>
      </template>
    </avue-crud>

    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update } from '@/api/product/charge-mixture';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';

export default {
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  name: '',
  data() {
    return {
      pageCode: 'CHARGE_MIXTURE',
      form: {},
      query: {},
      timer: null,
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      modalName: '',
      data: [],
      selectData: [],
      search: {},
      searchLabelWidth: 100,
      tableOption: {},
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        addBtnText: '登记',
        viewBtn: false,
        delBtn: false,
        selection: true,
        dialogClickModal: false,
        indexLabel: '序号',
        columnBtn: false,
        column: [
          {
            label: '料品',
            prop: 'partNo',
            type: 'search',
            search: true,
            disabled: true,
            formslot: true,
            appendClick: () => {
              this.openPartCommonModal();
            },
            rules: [
              {
                required: true,
                message: '请选择料品',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '投入产线',
            prop: 'lineName',
            type: 'search',
            disabled: true,
            appendClick: () => {
              this.openLineCommonModal();
            },
            rules: [
              {
                required: true,
                message: '请选择投入产线',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '数量',
            prop: 'quantity',
            controls: false,
            minRows: 0,
            type: 'number',
            rules: [
              {
                required: true,
                message: '请输入数量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '重量',
            prop: 'weight',
            type: 'number',
            minRows: 0,
            controls: false,
            rules: [
              {
                required: true,
                message: '请输入重量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark'
          },
          {
            label: '登记人',
            prop: 'operatorName'
          },
          {
            label: '时间',
            prop: 'createTime',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            searchType: 'datetimerange',
            search: true,
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期',
            addDisplay: false,
            editDisplay: false
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.charge_mixture_add, false),
        editBtn: this.vaildData(this.permission.charge_mixture_edit, false)
      };
    }
  },
  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });
  },
  methods: {
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.createTime && params.createTime.length > 0) {
        params.startTime = params.createTime[0];
        params.endTime = params.createTime[1];
        delete params.createTime;
      }
      if (this.search.partNo) {
        Object.assign(this.query, this.search);
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'partModal':
          this.search.partNo = this._get(rowData, 'partNo', '');
          this.$set(this.form, 'partNo', this._get(rowData, 'partNo', ''));
          this.form.partName = this._get(rowData, 'name', '');
          this.form.partModel = this._get(rowData, 'partModel', '');
          break;
        case 'lineModal':
          this.form.lineCode = this._get(rowData, 'code', '');
          this.form.lineName = this._get(rowData, 'name', '');
          this.form.lineId = this._get(rowData, 'id', '');
          break;
        default:
          break;
      }
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    /**
     * 重新加载公用表格弹窗组件
     *
     *
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 打开物料选择模态框
     */
    openPartCommonModal() {
      this.modalName = 'partModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择物料（双击进行选择）',
        url: '/api/mes-admin/part-master/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '物料名称',
            prop: 'name',
            search: true
          },
          {
            label: '物料分类',
            prop: 'categoryName'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '描述',
            prop: 'description'
          }
        ]
      };
    },
    /*
     * 打开产线选择模态框
     */
    openLineCommonModal() {
      this.modalName = 'lineModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择产线信息（双击进行选择）',
        url: '/api/mes-product/productionline/page',
        isPage: true,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        columnDefs: [
          {
            label: '产线名称',
            prop: 'name',
            search: true
          },
          {
            label: '产线编码',
            prop: 'code',
            search: true
          }
        ]
      };
    }
  }
};
</script>

<style></style>
